$(function(){
    $('.consultaCargando').css('display','none');
    $('.consultaCargandoImg').css('display','block');
    listEdificios();
    listRiesgos();
});

var busqueda = [];
var listTiposRiesgos = "";
var cantidadRiesgos = 0;

/* Actions-Catch
 * ****************************************************************************/
$('#edificios').change(function(){
    ed = $('#edificios :selected').val();
    if(ed == "") return;
    $('#spaceTittle').html(ed);
    $('#spaceImg').load('Modulo2/Templates/spaceImg.jsp?espacio='+ed.replace(" ", "", "gi"));
    getPisos(ed);
});

function resetRiesgos(){
    $('.tree-check').attr('checked',false);
    $(".simbolosR-item").removeClass('simbolosR-item-enable').addClass('simbolosR-item-disable');
    $(".simbolosR-image-enable").css('display','none');
    $(".simbolosR-image-disable").css('display','block');
}
function allRiesgos(){
    $('.tree-check').attr('checked',true);
    $(".simbolosR-item").removeClass('simbolosR-item-disable').addClass('simbolosR-item-enable');
    $(".simbolosR-image-disable").css('display','none');
    $(".simbolosR-image-enable").css('display','block');
}

function listRiesgos(){
    $.ajax({
        type: "POST",
        url: "listRiesgos.do",
        dataType: 'json',
        success: processListRiesgos
    });
    return false;
}

/* Process Acrions
* * **************************************************************************/
function processListRiesgos(answer){
    numRiesgo = 0;
    $('#simbolosR').html("");
    $.each(answer, function(index, value){
        treeItem = $("<div id='tree-item-"+index+"' class='tree-item'>");
        treeHead = $("<div id='tree-head-"+index+"' class='tree-head'>");
        treeHead.append($("<img alt='+' src='style/imagesTree/plus.gif' class='tree-head-img' id='tree-head-img-"+index+"'/>"));
        treeHead.append($("<input type='checkbox' class='tree-check tree-head-check' id='tree-head-check-"+index+"'/>  "));
        treeHead.append($("<div id='tree-head-tittle-"+index+"' class='tree-head-tittle'>").append(value.tipo));
        treeItem.append(treeHead);
        treeContent = $("<div id='tree-content-"+index+"' class='tree-content oculta'>");

        sTipoRiesgo = $("<div class='simbolosR-level'>");
        sTipoRiesgo.append($("<div class='simbolosR-tittle'>").append(value.tipo));
        sTipoRiesgoContent = $("<div class='simbolosR-content' id='simbolosR-content-"+index+"'>");

        idx=0;
        $.each(value.riesgos, function(index2, value2){
            treeContentItem = $("<div id='tree-content-item-"+index2+"' class='tree-content-item'>");
            treeContentItem.append($("<input name='factoresRiesgos' type='checkbox' class='tree-check tree-content-check tree-content-check-"+index+"' id='tree-content-check-"+numRiesgo+"' value='"+value2.riesgo+"'>"));
            treeContentItem.append($("<div class='tree-content-tittle' id='tree-content-tittle-"+numRiesgo+"'>"+value2.riesgo+"</div>"));
            treeContent.append(treeContentItem);

            sRiesgo = $("<div class='simbolosR-item simbolosR-item-disable"+"' id='simbolosR-item-"+value2.riesgo+"'>");
            sRiesgoImage = " <img alt='*' src='style/images/Mapas/Riesgos/bn/"+value2.riesgo+".gif' class='simbolosR-image simbolosR-image-disable muestra' id='simbolosR-image-"+value2.riesgo+"-disable'> ";
            sRiesgoImage += " <img alt='*' src='style/images/Mapas/Riesgos/"+value2.riesgo+".gif' class='simbolosR-image simbolosR-image-enable oculta' id='simbolosR-image-"+value2.riesgo+"-enable'> ";
            sRiesgo.append(sRiesgoImage);
            sRiesgo.append(value2.riesgo);
            sTipoRiesgoContent.append(sRiesgo);

            idx++;
            numRiesgo++;
        });
        treeContent.addClass('tree-content-size-'+idx);
        treeItem.append(treeContent);
        $('#riesgosTree').append(treeItem);
            
        sTipoRiesgo.append(sTipoRiesgoContent);
        $('#simbologiaRiesgos').append(sTipoRiesgo);
    });

    $("#riesgosWidget").toggleClass('muestra');
    $('#riesgosTree').append(controlsTree());

    $('#allChecks').click(allRiesgos);
    $('#resetChecks').click(resetRiesgos);
    $('.tree-head-img').click(function(){
        id = $(this).attr('id');
        treeIndex = id.replace('tree-head-img-', '', 'gi');
        content = $('#tree-content-'+treeIndex);
        if(content.hasClass('oculta')){
            content.removeClass('oculta').addClass('muestra');
            $('#tree-head-img-'+treeIndex).attr('src', 'style/imagesTree/minus.gif').attr('alt', '-');;
        } else {
            content.removeClass('muestra').addClass('oculta');
            $('#tree-head-img-'+treeIndex).attr('src', 'style/imagesTree/plus.gif').attr('alt', '+');;
        }
    });
    $('.tree-head-check').click(function(){
        id = $(this).attr('id');
        treeItemIndex = id.replace('tree-head-check-', '', 'gi');
        checked = $(this).attr('checked');
        $('.tree-content-check-'+treeItemIndex).attr('checked',checked);

        if(checked){
            $("#simbolosR-content-"+treeItemIndex+" .simbolosR-item").removeClass('simbolosR-item-disable').addClass('simbolosR-item-enable');
            $("#simbolosR-content-"+treeItemIndex+" .simbolosR-image-disable").css('display','none');
            $("#simbolosR-content-"+treeItemIndex+" .simbolosR-image-enable").css('display','block');
        } else {
            $("#simbolosR-content-"+treeItemIndex+" .simbolosR-item").removeClass('simbolosR-item-enable').addClass('simbolosR-item-disable');
            $("#simbolosR-content-"+treeItemIndex+" .simbolosR-image-enable").css('display','none');
            $("#simbolosR-content-"+treeItemIndex+" .simbolosR-image-disable").css('display','block');
        }
    });
    $('.tree-content-check').click(function(){
        checked = $(this).attr('checked');
        id = $(this).parent().parent().attr('id');
        treeItemIndex = id.replace('tree-content-', '', 'gi');
        riesgo = $(this).val()
        if(checked) {
            nro = $(this).attr('id').replace('tree-content-check-', '', 'gi');
            $('#factoresRiesgos').append($('#tree-content-tittle-'+nro).html()+"\n");
            n = $('#tree-content-'+treeItemIndex+' :checkbox:checked').size();
            if($('#tree-content-'+treeItemIndex).hasClass('tree-content-size-'+n))
                $('#tree-head-check-'+treeItemIndex).attr('checked',true);
            $("#simbolosR-item-"+riesgo).removeClass('simbolosR-item-disable').addClass('simbolosR-item-enable');
            $("#simbolosR-image-"+riesgo+"-disable").css('display','none');
            $("#simbolosR-image-"+riesgo+"-enable").css('display','block');
        }
        else {
            $('#tree-head-check-'+treeItemIndex).attr('checked',false);
            $("#simbolosR-item-"+riesgo).removeClass('simbolosR-item-enable').addClass('simbolosR-item-disable');
            $("#simbolosR-image-"+riesgo+"-enable").css('display','none');
            $("#simbolosR-image-"+riesgo+"-disable").css('display','block');
        }
    });
    $('.simbolosR-item-enable').live('click',function(){
        $('.simbolosR-item-current').removeClass('simbolosR-item-current');
        $(this).addClass('simbolosR-item-current');
        riesgo = $(this).attr('id').replace('simbolosR-item-', '', 'gi');
        setCategoria(riesgo);
    });

    $('.consultaCargandoImg').css('display','none');
    $('.consultaCargando').css('display','block');
}


/* Interface-Loaders
 * ****************************************************************************/
function consultarRiesgos(){
    $('#tableResult').css('display','none');
    $('.consultaCargandoImg').css('display','block');
    clearBusqueda();
    var listRiesgos = [];
    for (i=0; i < cantidadRiesgos; i++) {
        if(document.getElementById("tree-content-check-"+i).checked){
            listRiesgos.push(document.getElementById("tree-content-check-"+i).value);
        }
    }

    for (i in listRiesgos) {
        $('#resultado').empty();
        $.ajax({
            type: "POST",
            url: "listEspaciosRiesgo.do",
            dataType: 'json',
            data: {
                'riesgo': listRiesgos[i],
                'realizado': $('#realizado').val(),
                'factores': $('#factores').val(),
                'equipo': $('#equipo').val()
            },
            success: function(answer){
                $.each(answer.riesgos, function(index,value){
                    icon = 'style/images/Mapas/edificio3.gif';
                    latlng = new google.maps.LatLng(value.coordX,value.coordY);
                    var marker = new google.maps.Marker({
                        map: map,
                        position: latlng,
                        title: value.espacio,
                        icon: icon
                    });
                    var imagen = value.espacio.replace(/ /g, "");
                    google.maps.event.addListener(marker, 'click', function() {
                        content = "<div id='spaceTittle'>"+value.espacio+"</div>";
                        content += "<div id='spaceImg'><img src='style/images/Espacios/"+imagen+".jpg'/></div>";
                        content += "<div id='pisos'></div>";
                        $('#spaceInfo').html(content);
                        getPisos(value.espacio);
                    });
                    tr = $('<tr>');
                    tr.append($('<td>').append(value.riesgo));
                    tr.append($('<td>').append(value.realizado));
                    tr.append($('<td>').append(value.factores));
                    tr.append($('<td>').append(value.equipo));

                    $('#resultado').append(tr);
                    busqueda.push(marker);
                });
                $('#tableResult').css('display','block');
            }
        });
    }
    if(listRiesgos.length == 0){
        $('#resultado').empty();
        $.ajax({
            type: "POST",
            url: "listEspaciosRiesgo.do",
            dataType: 'json',
            data: {
                'riesgo': "",
                'realizado': $('#realizado').val(),
                'factores': $('#factores').val(),
                'equipo': $('#equipo').val()
            },
            success: function(answer){
                $.each(answer.riesgos, function(index,value){
                    icon = 'style/images/Mapas/edificio3.gif';
                    latlng = new google.maps.LatLng(value.coordX,value.coordY);
                    var marker = new google.maps.Marker({
                        map: map,
                        position: latlng,
                        title: value.espacio,
                        icon: icon
                    });
                    var imagen = value.espacio.replace(/ /g, "");
                    google.maps.event.addListener(marker, 'click', function() {
                        content = "<div id='spaceTittle'>"+value.espacio+"</div>";
                        content += "<div id='spaceImg'><img src='style/images/Espacios/"+imagen+".jpg'/></div>";
                        content += "<div id='pisos'></div>";
                        $('#spaceInfo').html(content);
                        getPisos(value.espacio);
                    });
                    tr = $('<tr>');
                    tr.append($('<td>').append(value.riesgo));
                    tr.append($('<td>').append(value.realizado));
                    tr.append($('<td>').append(value.factores));
                    tr.append($('<td>').append(value.equipo));

                    $('#resultado').append(tr);
                    busqueda.push(marker);
                });
                $('#tableResult #table').css('display','block');
                $('#tableResult #error').css('display','none');
            }
        });
    } else {
        $('#tableResult #table').css('display','none');
        $('#tableResult #error').css('display','block');
    }
    $('.consultaCargandoImg').css('display','none');
    $('#tableResult').css('display','block');
    return false;
}

// Removes the overlays from the map, but keeps them in the array
function clearBusqueda() {
    arreglo = busqueda;
    if (arreglo) {
        for (i in arreglo) {
            arreglo[i].setMap(null);
        }
    }
}

function processGetRisk(){
    clearEdificios();
    risks = answer.riesgos;
    $('#result').html("");
    table = $('<table>');
    $('#result').append(table);
    $.each(risks, function(index, value){
        i = 0;
        $.each(value, function(index2, value2){
            createMarker(value2.nombre_espacio,value2.coordX,value2.coordY,1);
            i++;
        });
        if(i>0){
            tr = $('<tr>');
            table.append(tr);

            tr.append('<th>'+index+'</th>');
            tr.append('<td>'+i+'</td>');
        }
    });
}
/* Actions
* ****************************************************************************/
function backUSB(){
    $("#map_Piso").css('display','none');
    $("#map_canvas").css('display','block');
}